package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Flavor;
import com.example.service.FlavorService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("flavors")
public class FlavorController {

    @Autowired
    private FlavorService flavorService;

    /**
     * 分页查询所有分类信息
     * @return
     */

    @GetMapping("/getPageFlavor/{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Flavor flavor){

        IPage page=new Page(currentPage,pageSize);
        LambdaQueryWrapper<Flavor> lqw =new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(flavor.getFlavorType()),Flavor::getFlavorType,flavor.getFlavorType());

        IPage page1 = flavorService.page(page,lqw);


        return R.success("分页查询所有flavors成功！",page1);
    }

    /**
     * 分页查询所有分类信息
     * @return
     */

    @GetMapping("/getAllFlavor")
    public R getAllFlavor(){
        List<Flavor> list = flavorService.list();

        return R.success("查询所有flavors成功！",list);
    }




    /**
     * 添加
     * @param flavor
     * @return
     */
    @PostMapping("/addFlavor")
    public R add(@RequestBody Flavor flavor){

        LambdaQueryWrapper<Flavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Strings.isNotEmpty(flavor.getFlavorType()),Flavor::getFlavorType,flavor.getFlavorType());
        Flavor flavor1=flavorService.getOne(lqw);

        if (flavor1==null) {
            Boolean update = flavorService.save(flavor);
            if (update) {
                return R.success("添加flavor成功!", null);
            }
        }
        return R.error("分类已存在");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @DeleteMapping("/deleteFlavor/{id}")
    public R deleteById(@PathVariable int id){

        Boolean byId = flavorService.removeById(id);
        if (byId){
            return R.success("删除flavors成功!",null);
        }
        return R.error("删除flavors失败!");
    }

    /**
     * 修改
     * @param flavor
     * @return
     */
    @PutMapping("/updateFlavor")
    public R deleteById(@RequestBody Flavor flavor){

        Boolean update = flavorService.updateById(flavor);
        if (update){
            return R.success("修改flavor成功!",flavor);
        }
        return R.error("修改flavor失败!");
    }


}

